package de.openkanban.client.util;

import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.smartgwt.client.util.JSON;

public abstract class JsonConverter {

	public static String getStringValueOrNull(String eingabe, String dtoAttributeName) {
		return getStringValueOrNull(new JSONObject(JSON.decode(eingabe)), dtoAttributeName);
	}

	public static String getStringValueOrNull(JSONObject jso, String dtoAttributeName) {
		if (jso != null) {
			if (jso.containsKey(dtoAttributeName)) {
				JSONValue value = jso.get(dtoAttributeName);
				if (value != null) {
					JSONString valueString = value.isString();
					if (valueString != null) {
						return valueString.stringValue();
					}
				}
			}
		}
		return null;
	}

	public static Long getLongValueOrNull(String eingabe, String dtoAttributeName) {
		return getLongValueOrNull(new JSONObject(JSON.decode(eingabe)), dtoAttributeName);
	}

	public static Long getLongValueOrNull(JSONObject jso, String dtoAttributeName) {
		if (jso != null) {
			if (jso.containsKey(dtoAttributeName)) {
				JSONValue value = jso.get(dtoAttributeName);
				if (value != null) {
					JSONNumber valueNumber = value.isNumber();
					if (valueNumber != null) {
						return (long) valueNumber.doubleValue();
					}
				}
			}
		}
		return null;
	}

	public static Integer getIntegerValueOrNull(String eingabe, String dtoAttributeName) {
		return getIntegerValueOrNull(new JSONObject(JSON.decode(eingabe)), dtoAttributeName);
	}

	public static Integer getIntegerValueOrNull(JSONObject jso, String dtoAttributeName) {
		if (jso != null) {
			if (jso.containsKey(dtoAttributeName)) {
				JSONValue value = jso.get(dtoAttributeName);
				if (value != null) {
					JSONNumber valueNumber = value.isNumber();
					if (valueNumber != null) {
						return (int) valueNumber.doubleValue();
					}
				}
			}
		}
		return null;
	}

	public static Boolean getBooleanValueOrNull(String eingabe, String dtoAttributeName) {
		return getBooleanValueOrNull(new JSONObject(JSON.decode(eingabe)), dtoAttributeName);
	}

	public static Boolean getBooleanValueOrNull(JSONObject jso, String dtoAttributeName) {
		if (jso != null) {
			if (jso.containsKey(dtoAttributeName)) {
				JSONValue value = jso.get(dtoAttributeName);
				if (value != null) {
					JSONBoolean valueBoolean = value.isBoolean();
					if (valueBoolean != null) {
						return (boolean) valueBoolean.booleanValue();
					}
				}
			}
		}
		return null;
	}
}
